/*************************************************************************
> File Name: isIPV4.c
> Author: hzy
> Created Time: 2023-09-18 19:22:05
> Description:
判断一个字符串是否是IPv4地址。如果是返回ture，否则返回false。同样不可以使用库函数。（实现函数）
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

bool isIPV4(char *ip_str)
{
    // char * ip_str = "10.7.178.180";
    int flag = false;
    int count = 0;
    char *p = ip_str;
    do
    {
        if (flag == true)
        {
            if (*ip_str == '.')
            {
                return false;
            }
            else
            {
                flag = false;
            }
        }

        if (*ip_str == '.')
        {
            flag = true;
            count++;
            ip_str++;
            continue;
        }
        if (*ip_str > '9' || *ip_str < '0')
        {
            return false;
        }
        ip_str++;
    } while (*ip_str != '\0');

    if (count != 3)
    {
        return false;
    }

    int arr[4] = {0};
    sscanf(p, "%d.%d.%d.%d", arr + 0, arr + 1, arr + 2, arr + 3);
    for (int i = 0; i < 4; i++)
    {
        if (arr[i] >= 0 && arr[i] <= 255)
        {
            cout << arr[i] << " ";
        }
        else
        {
            return false;
        }
    }
    cout << endl;

    return true;
}

int main(int argc, char const *argv[])
{
    cout << " IPV4 " << isIPV4("10.7.178.99") << endl;
    cout << " IPV4 " << isIPV4("..10.7.178.99") << endl;
    cout << " IPV4 " << isIPV4("10.7.178SS.99") << endl;
    cout << " IPV4 " << isIPV4("10.7.1758.99") << endl;

    return 0;
}